'use strict';

import mongoose, { mongo } from 'mongoose';
import config from '../config/default';
import chalk from 'chalk';
mongoose.set('useCreateIndex', true);
mongoose.connect(config.url, {
  socketTimeoutMS: 0,
  keepAlive: true,
  useNewUrlParser: true,
  useUnifiedTopology: true
});
mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.once('open', function() {
  console.log(
    chalk.green('连接数据库成功')
  );
})

db.on('error', function(error) {
  console.error(
    chalk.red('Error in MongoDB connection: ' + error)
  );
  mongoose.disconnect();
})

db.on('close', function() {
  console.log(
    chalk.red('数据库断开，重新连接数据库')
  );
  mongoose.connect(config.url, {server: {auto_reconnect: true}});
});

export default db;